﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Web.UI.HtmlControls;

using Gift.DAL;
using Gift.Model;

namespace WebSite.admin.order
{
    public partial class OrderAdd : BaseAdmin
    {
        readonly OrderAccount theOrderAccount = new OrderAccount();
        readonly DALCardType theCardType = new DALCardType();
        readonly DALGoods theGoods = new DALGoods();
        readonly DALCard theCard = new DALCard();
        readonly DALCar theDalCar = new DALCar();
        readonly DALtbTempCar theCar = new DALtbTempCar();
         readonly DALRegion theRegion = new DALRegion();
        tbCardType oCardType;
        List<tbProfessionAreaType> lstProfessionType = new List<tbProfessionAreaType>();
        readonly DALProfessionAreaType theProfessionAreaType = new DALProfessionAreaType();
        readonly MemberAccount theMemberAccount = new MemberAccount();
        readonly DALOrder theOrder = new DALOrder();

        public string address = "";
        public string carid = "0";
        public string carinfo = "";
        public string cname = "";
        public string email = "";
        public string istrue = "0";
        public string phone = "";
        public string post = "";
        public string score1 = "0";
        public string score2 = "0";
        public string score3 = "0";
        public string shipmsg = "";
        public string tel = "";
        public string totalprice = "0";
        public string totalscore = "0";

        DB_Order oOrder;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                
                base.ValidateLoginRule(Gift.Model.ENUM.ERule.AddOrder);
                if (Session["callerid"] != null)
                {
                    string callTel = string.Empty;
                    if (Session["callerid"].ToString().Length == 11)
                    {
                        this.txtMobile.Text = Session["callerid"].ToString();
                        callTel = this.txtMobile.Text;
                    }
                    else
                    {
                        this.txtTel.Text = Session["callerid"].ToString();
                        callTel = this.txtTel.Text;
                    }
                    oOrder = theOrder.GetModelByTel(callTel);
                    if (oOrder != null)
                    {
                        this.txtUserName.Text = oOrder.cname1;
                        string[] sAddress = oOrder.address1.Split(',');
                        if (sAddress.Length == 3)
                        {
                            this.txtAddress.Text = sAddress[2];
                        }
                        else
                        {
                            this.txtAddress.Text = oOrder.address1;
                        }
                    }


                }
                if (Request.QueryString["action"] == "del")
                {
                 
                    this.theOrderAccount.DeleOrderAccount(Request.QueryString["code"], int.Parse(Request.QueryString["id"]));
                    UserCardCodeList.RemoveAll(item => item.UserCardId == Request.QueryString["id"]);
                    ExtAspNet.Alert.Show("删除成功！");
                   
                    this.BuildCardInfo();
                    this.lblOrderCode.Text = Request.QueryString["code"];
                    
                }
                else
                {                
                    this.GenerateOrderCode();
                  
                }
                this.dpkSendTime.Text = DateTime.Now.AddDays(3).ToString("yyyy-MM-dd");
                this.BindPrivence();
                this.BindCity();
                this.BindArea();
                this.BuildCardInfo();
                this.BindAddGoodsGrid();
            }        

        }


        private void BindPrivence()
        {
            this.ddlSheng.Items.Clear();
            DataTable dtPrivence = theRegion.GetRegionByParentRegion(0);
            ddlSheng.DataTextField = "regionName";
            ddlSheng.DataValueField = "id";
            ddlSheng.DataSource = dtPrivence;
            ddlSheng.DataBind();

            ddlSheng.Items.Insert(0, new ExtAspNet.ListItem("选择省份", "-1"));
        }

        private void BindCity()
        {
            string sheng = ddlSheng.SelectedValue;
            this.ddlShi.Items.Clear();
            if (sheng != "-1")
            {
                DataTable dtCity = theRegion.GetRegionByParentRegion(int.Parse(sheng));
                this.ddlShi.DataTextField = "regionName";
                this.ddlShi.DataValueField = "id";
                ddlShi.DataSource = dtCity;
                ddlShi.DataBind();
            }

            ddlShi.Items.Insert(0, new ExtAspNet.ListItem("选择县区市", "-1"));
        }

        private void BindArea()
        {
            string shi = ddlShi.SelectedValue;
            this.ddlXian.Items.Clear();
            if (shi != "-1")
            {
                DataTable dtArea = theRegion.GetRegionByParentRegion(int.Parse(shi));
                this.ddlXian.DataTextField = "regionName";
                this.ddlXian.DataValueField = "id";
                ddlXian.DataSource = dtArea;
                ddlXian.DataBind();
            }
            if (ddlXian.Items.Count <= 0)
            {
                ddlXian.Items.Insert(0, new ExtAspNet.ListItem("选择地区市", ""));
            }
            else
            {
                ddlXian.Items.Insert(0, new ExtAspNet.ListItem("选择地区市", "-1"));
            }
        }

        private void BindAddGoodsGrid()
        {  
            DataTable table = theCar.GetListByOrderCode(this.lblOrderCode.Text.Trim());
            Grid1.DataSource = table;
            Grid1.DataBind();

        }



        void GenerateOrderCode()
        {
            if (this.lblOrderCode.Text == "")
            {
                if (!string.IsNullOrEmpty(Request.QueryString["orderCode"]))
                {
                    this.lblOrderCode.Text = Request.QueryString["orderCode"];
                }
                else
                {
                    this.lblOrderCode.Text = theOrderAccount.GenerateOrderCode();
                }
            }
        }

        void BuildCardInfo()
        {
            StringBuilder sbCardInfo = new StringBuilder();
            if (UserCardCodeList != null && UserCardCodeList.Count > 0)
            {
                this.hdCardCode.Text = UserCardCodeList[0].UserCardCode;
                foreach (UserCard uc in UserCardCodeList)
                {
                    oCardType = theCardType.GetModel(int.Parse(uc.UserCardTypeId));
                    sbCardInfo.AppendFormat("卡号:{0},福点数:{1},卡类别:{3}<a href='OrderAdd.aspx?action=del&id={4}&code={5}'>删除</a><br/>"
                                            , uc.UserCardCode
                                            , uc.UserCardPrice
                                            , uc.UserCardTypeId
                                            , oCardType.Name
                                            , uc.UserCardId
                                            , this.lblOrderCode.Text.Trim()
                                            );

                    if (uc.UseWay == 1)
                    {
                        if (!this.hdCardTypes.Text.Contains("-" + uc.UserCardTypeId))
                        {
                            this.hdCardTypes.Text = this.hdCardTypes.Text + "-" + uc.UserCardTypeId;
                        }
                    }
                } 
            }
        
            lblCardInfo.Text = sbCardInfo.ToString();
            this.txtCardCode.Text = "";
            this.txtCardPass.Text = "";
          
        }




        protected void btnSubmitOrder_Click(object sender, EventArgs e)
        {
            if (UserCardCodeList == null)
            {
                ExtAspNet.Alert.Show("请选择添加新订单或者选择未完成的订单！");
                return;
            }
            DB_Order oOrder = new DB_Order();
            tbTempCar oCar = new tbTempCar();
            int dSumCardPoints = 0;
            int dGoodsPoints = 0;

            if (UserCardCodeList == null || UserCardCodeList.Count <= 0)
            {
                ExtAspNet.Alert.Show("您还没有选取要购买商品！");
                return;
            }

            foreach (UserCard uc in UserCardCodeList)
            {
                DB_Card oTmpCard;
                oTmpCard = theCard.GetModel(long.Parse(uc.UserCardCode), uc.UserCardPassword);
                if (oTmpCard == null || (oTmpCard.states != 1 && oTmpCard.states != 5))
                {
                    ExtAspNet.Alert.Show("卡号(" + uc.UserCardCode + "),此卡已被使用，请删除后，请重新添加！");
                    return;
                }
                dSumCardPoints = dSumCardPoints + oTmpCard.cardprice;
            }



                DataTable dtGoods = theCar.GetListByOrderCode(this.lblOrderCode.Text.Trim());
      
                if (dtGoods == null || dtGoods.Rows.Count <= 0)
                {
                    ExtAspNet.Alert.Show("该卡暂没有要兑换的商品！");
                    return;
                }
                else
                {
                    foreach (DataRow dr in dtGoods.Rows)
                    {

                        dGoodsPoints += int.Parse(dr["sumGoodsPoints"].ToString());
                    }

                }
            

            if (dSumCardPoints != dGoodsPoints)
            {
                ExtAspNet.Alert.Show("卡内福点数与商品福点数不一致，请得新选择商品！");
                return;
            }


            oOrder.ordercode =  this.lblOrderCode.Text.Trim();
            oOrder.pay = "礼品卡";
            oOrder.states = 0;
            oOrder.cname = base.AdminUser;
            oOrder.cname1 = this.txtUserName.Text.Trim();
            oOrder.tel1 = this.txtTel.Text.Trim();
           oOrder.phone1 = this.txtMobile.Text.Trim();
            oOrder.post1 = this.txtPostcode.Text.Trim();
            string sXian = this.ddlXian.SelectedItem.Value == "-1" ? "" : this.ddlXian.SelectedItem.Text + ",";
            oOrder.address1 = this.ddlSheng.SelectedItem.Text + "," + this.ddlShi.SelectedItem.Text + "," + sXian + this.txtAddress.Text.Trim();
           oOrder.senddate = this.dpkSendTime.Text.Trim() == "" ? DateTime.Now.AddDays(3) : DateTime.Parse(this.dpkSendTime.Text.Trim()); 
            oOrder.ordertime = DateTime.Now;
            oOrder.cardprice = dSumCardPoints;
            oOrder.totalprice = dSumCardPoints.ToString();
            oOrder.content = this.txtRemark.Text.ToString();
            oOrder.orderid =   theOrder.Add(oOrder);
            DALCar theDalCar = new DALCar();
            theDalCar.AddTempToReal(this.lblOrderCode.Text.Trim());
            theOrderAccount.UpdateComplateAccount(this.lblOrderCode.Text.Trim());
            UserCardCodeList = null;
            ExtAspNet.Alert.Show("提交订单成功！请记住订单编号(" + oOrder.ordercode + ")以便查询！", "", "window.location.href='orders.aspx?oid=" + oOrder.orderid.ToString() + "&flag=2'");

        }

        protected void Grid1_Sort(object sender, ExtAspNet.GridSortEventArgs e)
        {

        }

        //添加卡片
        protected void btnCardAdd_Click(object sender, EventArgs e)
        {
       
            //System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();
            //s.Start();

            if (string.IsNullOrEmpty(this.lblOrderCode.Text.Trim()))
            {
                ExtAspNet.Alert.Show("请添加新订单！");
             
                return;
            }
            DB_Card oCard = null;
               oCard = theCard.GetModel(long.Parse(this.txtCardCode.Text.Trim()), this.txtCardPass.Text.Trim());
            if (oCard != null)
            {
                if (oCard.states == 0)
                {
                    ExtAspNet.Alert.Show("该卡还处于未发行状态，不能进行兑换！");
                }
                else if (oCard.states == 2)
                {
                    ExtAspNet.Alert.Show("该卡已被使用！");
                }
                else if (oCard.states == 3)
                {
                    ExtAspNet.Alert.Show("该卡还处于禁用状态，不能进行兑换！");
                }
                else if (oCard.states == 4)
                {
                    ExtAspNet.Alert.Show("该卡处于已领用未激活状态,请先开卡后才能使用！");
                }
                else if (oCard.StartTime > DateTime.Now.Date)
                {
                    ExtAspNet.Alert.Show("该卡还未到兑换时间！");
                }
                else if (oCard.endtime < DateTime.Now.Date)
                {
                    ExtAspNet.Alert.Show("该卡已过有效兑换时间！");
                }
                else if (oCard.states == 1)
                {
                    theOrderAccount.AddCardToCardAccount(this.lblOrderCode.Text.Trim(), oCard.cardid);
                    UserCard oUserCard = new UserCard();
                    oUserCard.UserCardId = oCard.cardid.ToString();
                    oUserCard.UserCardCode = oCard.cardcode;
                    oUserCard.UserCardPassword = Gift.Security.DESEncrypt.Decrypt(oCard.cardpas);
                    oUserCard.UserCardPrice = oCard.cardprice.ToString();
                    oUserCard.UserCardTypeId = oCard.cardtypeId.ToString();
                    oUserCard.UseWay = oCard.UseWay;
                    if (UserCardCodeList == null || !UserCardCodeList.Exists(item => item.UserCardId == oUserCard.UserCardId))
                    {

                        if (UserCardCodeList == null)
                        {
                            UserCardCodeList = new List<UserCard>();
                            UserCardCodeList.Add(oUserCard);
                        }
                        else
                        {
                            if (UserCardCodeList.Count>0 && UserCardCodeList[0].UseWay != oCard.UseWay)
                            {
                                if (oCard.UseWay == 1)
                                {
                                    ExtAspNet.Alert.Show("您使用的是专区类型的卡，不能与通用类型的卡同时使用！");
                                }
                                else
                                {
                                    ExtAspNet.Alert.Show("您使用的是通用类型的卡，不能与专区类型的卡同时使用！");
                                }
                                return;
                            }
                            else
                            {
                                if (UserCardCodeList.Count > 0 && UserCardCodeList[0].UserCardTypeId != oCard.cardtypeId.ToString())
                                {
                                    ExtAspNet.Alert.Show("只能同时添加同一类型的专区类卡！");
                                }
                                else
                                {
                                    UserCardCodeList.Add(oUserCard);
                                }
                            }
                        }
                    }

                    this.BuildCardInfo();
                
                   // s.Stop();
                }
            }
            else
            {
                ExtAspNet.Alert.Show("卡号或密码不正确！");
            }

        }

        protected void ddlSheng_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindCity();
        }

        protected void ddlShi_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindArea();
        }

        protected void Window1_Close(object sender, EventArgs e)
        {
            this.BindAddGoodsGrid();
           // ExtAspNet.Alert.Show("postback回发窗口！");
        }

        protected void Window2_Close(object sender, EventArgs e)
        {
            this.BindAddGoodsGrid();
            // ExtAspNet.Alert.Show("postback回发窗口！");
        }

        protected void Grid1_RowCommand(object sender, ExtAspNet.GridCommandEventArgs e)
        {
            
            if (e.CommandName == "deleted")
            {
                theCar.Delete(this.lblOrderCode.Text.Trim(), int.Parse( Grid1.DataKeys[e.RowIndex][0].ToString()));
                ExtAspNet.Alert.Show("商品删除成功！");
                this.BindAddGoodsGrid();
            
            }


        }



    }
}